package com.example.memorycardgame.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CardMatchingGame {
    private List<Card> cards;
    private List<Integer> chosenCardIndices; // 记录选中的卡片索引
    private int score;

    public CardMatchingGame(int cardCount) {
        score = 0;
        chosenCardIndices = new ArrayList<>();
        initCards(cardCount);
    }

    private void initCards(int cardCount) {
        cards = new ArrayList<>();
        // 生成卡片（每种图案重复3次，共24张则需要8种图案）
        List<Integer> imageResIds = new ArrayList<>();
        for (int i = 1; i <= 8; i++) {
            for (int j = 0; j < 3; j++) {
                imageResIds.add(getImageResId(i));
            }
        }
        Collections.shuffle(imageResIds);

        for (int i = 0; i < cardCount; i++) {
            cards.add(new Card(imageResIds.get(i), i));
        }
    }

    private int getImageResId(int index) {
        // 假设卡片资源为ic_card1到ic_card8
        return getResources().getIdentifier("ic_card" + index, "drawable", getPackageName());
    }

    public Card getCard(int index) {
        return cards.get(index);
    }

    public int getScore() {
        return score;
    }

    public boolean chooseCardAtIndex(int index) {
        Card card = cards.get(index);
        if (card.isMatched() || card.isFlipped()) return false;

        card.flip();
        chosenCardIndices.add(index);

        // 3张牌匹配逻辑
        if (chosenCardIndices.size() == 3) {
            boolean isMatch = true;
            int firstResId = cards.get(chosenCardIndices.get(0)).getImageResId();
            for (int i = 1; i < 3; i++) {
                if (cards.get(chosenCardIndices.get(i)).getImageResId() != firstResId) {
                    isMatch = false;
                    break;
                }
            }

            if (isMatch) {
                // 匹配成功，加分
                score += 15;
                for (int i : chosenCardIndices) {
                    cards.get(i).setMatched(true);
                }
            } else {
                // 匹配失败，扣分
                score = Math.max(0, score - 5);
                for (int i : chosenCardIndices) {
                    cards.get(i).flip(); // 翻回背面
                }
            }
            chosenCardIndices.clear();
        }
        return true;
    }

    public void reset() {
        score = 0;
        chosenCardIndices.clear();
        initCards(cards.size());
    }

    // 用于获取资源（需在Activity中实现上下文获取，或调整类结构）
    private Resources getResources() {
        // 实际项目中需通过上下文获取，此处为示例，需根据项目结构调整
        return App.getAppContext().getResources();
    }
}